<template>
  <view class="page-container" :scroll-top="scrollTop">
    <!-- 弹窗标题 -->
    <view class="header">
      <text class="title">模板格式维护</text>
    </view>

    <!-- 新增/修改表单（仅在 isFormVisible 为 true 时显示） -->
    <view v-if="isFormVisible" class="form-section">
      <view class="input-group">
        <text class="label">模板名称：</text>
        <input
          class="input"
          v-model="formData.templateName"
          placeholder="请输入模板名称"
        />
      </view>

      <view class="input-group">
        <text class="label">模板内容：</text>
        <input
          class="input"
          v-model="formData.templateContent"
          placeholder="请输入模板内容"
        />
      </view>

      <view class="actions">
        <button class="btn-submit" @click="submitForm">
          {{ isEditing ? '确认修改' : '提交新增' }}
        </button>
      </view>
    </view>

    <!-- 模板列表 -->
    <scroll-view scroll-y class="template-list" :scroll-top="scrollTop">
      <view v-for="(item, index) in templates" :key="index" class="template-card">
        <!-- 模板名称 -->
        <view class="input-group">
          <text class="label">模板名称：</text>
          <text>{{ item.templateName }}</text>
        </view>

        <!-- 模板内容 -->
        <view class="input-group">
          <text class="label">模板内容：</text>
          <text>{{ item.templateContent }}</text>
        </view>

        <!-- 操作按钮 -->
        <view class="actions">
          <button size="mini" type="primary" plain @click="handleEdit(item)">
            修改
          </button>
          <button size="mini" type="default" plain @click="deleteTemplate(item.templateId)">
            删除
          </button>
        </view>
      </view>
    </scroll-view>

    <!-- 新增按钮始终固定在底部右侧 -->
    <button class="btn-mini-fixed" @click="showAddForm">新增模板</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      templates: [],
      // 表单控制
      isFormVisible: false,
      isEditing: false,
      formData: {
        templateId: null,
        templateName: '',
        templateContent: ''
      },
      scrollTop: 0 // 控制滚动到顶部
    };
  },
  onLoad() {
    this.fetchTemplates();
  },
  methods: {
    async fetchTemplates() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8083/template',
          method: 'GET'
        });
        this.templates = res.data;
      } catch (err) {
        uni.showToast({ title: '没连上后台你个笨蛋', icon: 'none' });
      }
    },

    // 点击“新增模板”按钮时显示表单
    showAddForm() {
      this.isFormVisible = true;
      this.isEditing = false;
      this.formData = {
        templateName: '',
        templateContent: '',
        templateId: null
      };

      // 自动滚动到顶部
      this.scrollTop = 0;
    },

    // 点击“编辑”按钮时触发
    handleEdit(item) {
      this.isFormVisible = true;
      this.isEditing = true;
      this.formData = { ...item }; // 数据回显
      this.scrollTop = 0; // 滚动到顶部
    },

    // 提交表单（新增 or 修改）
    async submitForm() {
      const { templateName, templateContent } = this.formData;

      if (!templateName || !templateContent) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }

      try {
        if (this.isEditing && this.formData.templateId) {
          // 修改已有模板
          await uni.request({
            url: 'http://localhost:8083/template',
            method: 'PUT',
            data: this.formData
          });
          uni.showToast({ title: '修改成功', icon: 'success' });

          this.fetchTemplates();

        } else {
          // 新增模板
          const res = await uni.request({
            url: 'http://localhost:8083/template/save',
            method: 'POST',
            data: this.formData
          });

          uni.showToast({ title: '新增成功', icon: 'success' });

          this.fetchTemplates();
          
        }

        this.isFormVisible = false; // 提交后隐藏表单
      } catch (err) {
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    },

    async deleteTemplate(templateId) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该模板吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await uni.request({
                url: `http://localhost:8083/template/${templateId}`,
                method: 'DELETE'
              });
              uni.showToast({ title: '删除成功', icon: 'success' });
              this.fetchTemplates();
            } catch (err) {
              uni.showToast({ title: '删除失败', icon: 'none' });
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 30rpx;
  background-color: #f9f9f9;
  position: relative;
}

.header {
  margin-bottom: 40rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
}

.input-group {
  margin-bottom: 20rpx;
}
.label {
  font-size: 26rpx;
  color: #666;
  margin-right: 20rpx;
}
.input {
  border: 1px solid #ddd;
  padding: 12rpx 20rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-submit {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  background-color: #07c160;
  color: white;
  border-radius: 8rpx;
}

.template-list {
  height: calc(100vh - 250rpx);
}

.template-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
}

.actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
}
.actions button {
  margin-left: 20rpx;
  font-size: 24rpx;
  padding: 0 24rpx;
  height: 56rpx;
  line-height: 56rpx;
}

/* 固定新增按钮 */
.btn-mini-fixed {
  position: fixed;
  right: 30rpx;
  bottom: 30rpx;
  width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 26rpx;
  padding: 0;
  border-radius: 8rpx;
  background-color: #07c160;
  color: white;
}
</style>